public with sharing class MeasureCalcPreController {

    public List<IntentProductBean> qpList { get; set; }
    public List<Measure_Calculate_ProductBean> mcpbList {get;set;}
    public Measure_Calculate__c mc { get; set; }//新建或者编辑的测算信息
    public Measure_Calculate__c oldmc ;//上次审批通过的测算信息;

    public String mcId { get; private set; }  // 测算Id
    public String qId { get; private set; }  // 报价Id
    public String oppId {get; private set;} //业务机会Id 
    public Boolean cantSeeYield { get; private set ; }

    public Boolean isApproaling {get; private set;}
    public User u ;
    public Opportunity opp {get;private set;}//业务机会
    public Boolean isSuccess {get;private set;}//是否保存成功
    private String oldAdditionalService;

    public MeasureCalcPreController (ApexPages.StandardController stdController) {
        qpList = new List<IntentProductBean>();

        mcId = stdController.getId();
         
        oppId =System.currentPageReference().getParameters().get('oppid');
        cantSeeYield = false;

        mcpbList = new List<Measure_Calculate_ProductBean>();

        u = [select SubCompany__c, Profile.Name from User where Id = :UserInfo.getUserId()];

System.debug('+++' +u.SubCompany__c);
        isApproaling = false;
    }

    public void init() {

        mc = new Measure_Calculate__c();
        oldmc = new Measure_Calculate__c();//上次审批通过的测算信息;


        // 编辑
        if (String.isBlank(mcId) == false) {
            Schema.DescribeSobjectResult m = Measure_Calculate__c.sObjectType.getDescribe();
            Map<String, Schema.SObjectField> fieldMap = m.fields.getMap();

            String sql = 'select ';
            String fields = '';
            for (String field : fieldMap.keySet()) {
                if (fields.length() > 0) {
                    fields += ', '; 
                }
                fields += field;
            }
            sql += fields;
            sql += ',Opportunity__r.Account.Name,Opportunity__r.Account.Level__c,Opportunity__r.Account.LISRevenue__c ';
            sql += ' from Measure_Calculate__c where Id = \'' + mcId + '\'';
            mc = Database.query(sql);
            //qId = mc.Quote__c;
             mc.Company__c =  u.SubCompany__c;
            getEquipmentFromMeasure_Calculate(mc.Id);
            oppId = mc.Opportunity__c;
            if(mc.Status__c == '审批成功' || mc.Status__c == '已提交')isApproaling = true;
            if(isApproaling == true)  ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, '测算提交审批中或审批通过不能修改!'));
 
        }
        // 新建
        else if (String.isBlank(oppId) == false) {
               //设置测算对应的公司 
            ///获取测算信息
            getMessureCalc();

            mc.Company__c =  u.SubCompany__c;

           

        } 

        opp = [select Id ,Account.Name ,Account.Level__c ,Account.LISRevenue__c from Opportunity where Id =:oppId];
        
      



        ///从意向产品中带出仪器
       if(oppId != null) getEquipmentFromIntentProduct();


        String completion = System.currentPageReference().getParameters().get('c');
        if (String.isBlank(completion) == false) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, System.Label.Save_OK));
        }


        oldAdditionalService = mc.AdditionalService__c;

        // 销售员及其主管只能填写标本量
        Set<String> profileSet = new Set<String>(System.Label.Rt_CantSeeYield.split(','));
        if (profileSet.contains(u.Profile.Name)) cantSeeYield = true;
        
    }
    ///新建测算 
    public void getMessureCalc(){
    	///查询当前有没
        //List<Measure_Calculate__c> mcList = [select Id from Measure_Calculate__c 
         //                                    where Opportunity__c =:oppId  and (Status__c ='审批成功' or Status__c ='审批拒绝')];

            Schema.DescribeSobjectResult m = Measure_Calculate__c.sObjectType.getDescribe();
            Map<String, Schema.SObjectField> fieldMap = m.fields.getMap();

            String sql = 'select ';
            String fields = '';
            for (String field : fieldMap.keySet()) {
                if (fields.length() > 0) {
                    fields += ', '; 
                }
                fields += field;
            }
            sql += fields;
            sql += ',Opportunity__r.Account.Name,Opportunity__r.Account.Level__c,Opportunity__r.Account.LISRevenue__c ';
   
            sql += ' from Measure_Calculate__c where Opportunity__c = \'' + oppId + '\' and (Status__c =\'审批成功\' or Status__c =\'审批拒绝\' )order by createddate desc limit 1';
            List<Measure_Calculate__c> mcList = Database.query(sql);
            if(mcList.size()>0){
                oldmc = mcList[0];
                mc = oldmc.clone();
                mc.LastMeasureCalc__c = oldmc.Id ;
                mc.Id = null;
                mc.IsActive__c = false;
            }
            
			
            mc.Status__c = '草案中';


       /* } else {
            Schema.DescribeSobjectResult m = Measure_Calculate__c.sObjectType.getDescribe();
            Map<String, Schema.SObjectField> fieldMap = m.fields.getMap();

            String sql = 'select ';
            String fields = '';
            for (String field : fieldMap.keySet()) {
                if (fields.length() > 0) {
                    fields += ', '; 
                }
                fields += field;
            }
            sql += fields;
           sql += ',Opportunity__r.Account.Name,Opportunity__r.Account.Level__c,Opportunity__r.Account.LISRevenue__c ';

            sql += ' from Measure_Calculate__c where Id = \'' + mcList[0].Id + '\'';
            mc = Database.query(sql);

        }*/
        ///如果存在上次审批通过的测算 则带入上次测算通过仪器
       
        if(mc.LastMeasureCalc__c != null)getEquipmentFromMeasure_Calculate(mc.LastMeasureCalc__c);

    }
    //从测算产品中带入仪器
    public void getEquipmentFromMeasure_Calculate(String mcId){

        Schema.DescribeSobjectResult m = Measure_Calculate_Product__c.sObjectType.getDescribe();
        Map<String, Schema.SObjectField> fieldMap = m.fields.getMap();

        String sql = 'select ';
        String fields = '';
        for (String field : fieldMap.keySet()) {
            if (fields.length() > 0) {
                fields += ', '; 
            }
            fields += field;
        }
        sql += fields;
        sql += ',  Product__r.Name from Measure_Calculate_Product__c where Measure_Calculate__c = \'' + mcId + '\' and IsEquipRelated__c = true ';
       List<Measure_Calculate_Product__c> temp = Database.query(sql);
       Set<Id>  pids= new Set<Id>();
       for ( Measure_Calculate_Product__c mcp : temp) {
           pids.add(mcp.Product__c);
       }
     Map <Id,Price__c> priceMap = getPriceMap(pids);
       mcpbList.clear();
       for(Measure_Calculate_Product__c mcp : temp){
       		mcpbList.add(new Measure_Calculate_ProductBean(mcp,priceMap.get(mcp.Product__c),mc.Company__c));
       }
       System.debug('带入的仪器'+mcpbList);

    }

    //从意向产品中带出仪器到测算
    public void getEquipmentFromIntentProduct(){


        // 把仪器从意向产品带过来
        Schema.DescribeSobjectResult m = IntentProduct__c.sObjectType.getDescribe();
        Map<String, Schema.SObjectField> fieldMap = m.fields.getMap();

        String sql = 'select ';
        String fields = '';
        for (String field : fieldMap.keySet()) {
            if (fields.length() > 0) {
                fields += ', '; 
            }
            fields += field;
        }
        sql += fields;
        sql += ' ,  Product__r.Name,Product__r.Category0__c,Product__r.Category1__c,Product__r.Brand__c from IntentProduct__c where Opportunity__c = \'' + oppId + '\' and Product__r.Category0__c not in (\'试剂\',\'耗材\',\'校准\',\'质控\',\'耗品\',\'试纸\',\'第三方产品\',\'配件\') ';
       List<IntentProduct__c> ipList = Database.query(sql);
        
        Set<Id> pidset = new Set<Id>();
        for(IntentProduct__c ip : ipList){
            pidset.add(ip.Product__c);

        }
        Map<Id,Price__c> priceMap = new Map<Id,Price__c>();
        if(pidset.size()> 0)priceMap = getPriceMap(pidset);
        for(IntentProduct__c ip : ipList){

            qpList.add(new IntentProductBean(ip,priceMap.get(ip.Product__c)));
        }




    }
    ///获取价格
  private Map<Id,Price__c> getPriceMap(Set<Id> pids){


  Map<Id, Price__c> priceMap = new Map<Id, Price__c>();
            for (Price__c pr : [select Id, Product__c,Product__r.bggsjhdj__c, MarketPrice__c, HospitalManagerPrice__c, HospitalBottomPrice__c, CompanyBottomPrice__c,
                AreaDealerPrice__c, InvoiceDealerPrice__c, RepairCost__c, InstCost__c ,LastMonthAveragePrice__c,Taxrate__c,Subsidiary_price__c 
                                from Price__c where Product__c in : pids and Company__c = :mc.Company__c]) {
                priceMap.put(pr.Product__c, pr);
            }
      return priceMap;
  
  }
    
    public  void save() {
        System.Savepoint  sp = Database.setSavepoint() ;
        try {
            if(mcpbList.size() == 0) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '请选择仪器!'));
                return ;
            }

            
            if (mc.Opportunity__c == null) {
                mc.Opportunity__c = oppId;
            }
                for(Measure_Calculate_ProductBean mcpb : mcpbList){
                    if(String.isBlank(mcpb.mcp.CoopType__c) == true ) {
                        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '仪器的合作类型必填!'));
                        return ; 
                    }
                 }
                  upsert mc;   
           
			if(mc.Id != null){
				
				List<Measure_Calculate_Product__c> equipList = new List<Measure_Calculate_Product__c>();
			     System.debug('现在有的仪器'+ mcpbList);

				for(Measure_Calculate_ProductBean mcpb : mcpbList){
                   	Measure_Calculate_Product__c mcp = new Measure_Calculate_Product__c();
					mcp = mcpb.mcp;
                    mcp.Id = null;
					mcp.Measure_Calculate__c = mc.Id;
                    mcp.IsEquipRelated__c = true;
					equipList.add(mcp);
				}
                List<Measure_Calculate_Product__c> mcp_equipList =[select Id from Measure_Calculate_Product__c 
                where Measure_Calculate__c =:mc.Id and IsEquipRelated__c = true];
                if(mcp_equipList.size() > 0)delete mcp_equipList;

				if(equipList.size()>0) insert equipList;
                
				
			}

			
            //update qpList;
            // 如果增值类服务发生了变动
            List<AdditionalService__c> asDelList = [select Id from AdditionalService__c where MeasureCalc__c = :mc.Id];

            if ((asDelList.size() == 0 && mc.AdditionalService__c != null )||(oldAdditionalService != mc.AdditionalService__c)) {
                // 根据增值类服务（多选）新建记录
                if (asDelList.size() > 0) delete asDelList;
                if (String.isBlank(mc.AdditionalService__c) == false) {
                    List<AdditionalService__c> asInsList = new List<AdditionalService__c>();
                    for (String opt : mc.AdditionalService__c.split(';', -1)) {
                        asInsList.add(new AdditionalService__c(
                            Name = opt,
                            MeasureCalc__c = mc.Id
                        ));
                    }
                    insert asInsList;
                }
            }

            mcId = mc.Id;
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, '保存成功!'));
            isSuccess = true;

        } catch (Exception e) {
            Database.rollback(sp);
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, e.getMessage()));
        }
    }
    public void exchange(){
		List<Measure_Calculate_ProductBean> stayList = new List<Measure_Calculate_ProductBean>();
		Set<String> extendIds = new Set<String>();

		//如果没有选中则保留
		for(Measure_Calculate_ProductBean mcp :mcpbList){
			if(mcp.chk == false){
				stayList.add(mcp);
				extendIds.add(mcp.mcp.Product__c);
			}
		}

		mcpbList.clear();
		mcpbList.addAll(stayList);
		//选中的意向产品

        
		for(IntentProductBean ipb : qpList){
			
			if(ipb.chk == true && !extendIds.contains(ipb.ip.Product__c)){
				mcpbList.add(new Measure_Calculate_ProductBean(ipb.ip,ipb.price,mc.Company__c));
			}
			ipb.chk = false;
		}
    }
    public class Measure_Calculate_ProductBean{
       
        public String ProductName {get;set;}//产品名称
        public Measure_Calculate_Product__c mcp {get;set;}//测算产品
        public Boolean chk {get;set;}
       
        
        public  Measure_Calculate_ProductBean(IntentProduct__c p,Price__c pr,String com){
            ProductName = p.Product__r.Name;
            //
            mcp = new Measure_Calculate_Product__c();
            mcp.Product__c = p.Product__c;
            mcp.Quantity__c = p.Quantity__c;
            //ProductId = p.Product__c;
            // Quantity = p.Quantity__c;
            mcp.SalesPriceWT__c = p.SalesPrice__c;
            mcp.Category0__c = p.Product__r.Category0__c;
            mcp.Brand__c = p.Product__r.Brand__c;
            mcp.ProductLine__c = p.Product__r.Category1__c;
            mcp.CoopType__c = p.CoopType__c;
            mcp.InstCost__c = pr != null ? pr.InstCost__c : 0 ;//集团成本(价格 成本价)
            mcp.DealerInstCost__c = pr != null ? pr.AreaDealerPrice__c : 0;//经销商成本(价格 区域经销商价)
            mcp.SubInstCost__c = pr != null ? getSubCompanyPrice(com,pr) : 0;//子公司价（云南、贵州、重庆、四川-实业，生物 几个公司取价格体系中的成本价）
            mcp.RepairCost__c = pr != null ? Pr.RepairCost__c : 0 ;

        }
         ///子公司成本价格
      public Decimal getSubCompanyPrice(String com,Price__c pr){

            if (com == '四川省迈克实业有限公司'||
                com == '重庆征途科技有限公司'||
                com == '云南迈克科技有限公司'||
                com == '贵州迈克科技有限公司'||
                com == '四川迈克生物医疗电子有限公司') {

                return pr.InstCost__c;
                
            }
            return pr.Subsidiary_price__c;
        }

        public Measure_Calculate_ProductBean(Measure_Calculate_Product__c p,Price__c pr,String com){
            ProductName =  p.Product__r.name;
            mcp = p;
            mcp.IsEquipRelated__c = true;
            mcp.InstCost__c =(p.InstCost__c == null  || p.InstCost__c== 0 )? pr != null ? pr.InstCost__c : 0:p.InstCost__c ;//集团成本(价格 成本价)
            mcp.DealerInstCost__c =(p.DealerInstCost__c == null || p.DealerInstCost__c == 0) ? pr != null ? pr.AreaDealerPrice__c : 0 :p.DealerInstCost__c;//经销商成本(价格 区域经销商价)
            mcp.SubInstCost__c = (p.SubInstCost__c == null || p.SubInstCost__c == 0) ? pr != null ? getSubCompanyPrice(com,pr) : 0 : P.SubInstCost__c;//子公司价（云南、贵州、重庆、四川-实业，生物 几个公司取价格体系中的成本价）
            mcp.RepairCost__c = (p.RepairCost__c == null || p.RepairCost__c == 0) ? pr != null ? pr.RepairCost__c : 0 : p.RepairCost__c;//报修成本
           
        }


    }
    public class IntentProductBean{
        public Boolean chk {get;set;}
      	public IntentProduct__c ip {get;set;}
        public Price__c price {get;set;}
       public IntentProductBean(IntentProduct__c p,Price__c pr){
            ip = p;
            price = pr; 
        }
        
    }  


}